#encoding=utf8
'''
Detection with SSD
In this example, we will load a SSD model and use it to detect objects.
'''
import time
start=time.clock()
import os
import sys
import argparse
import numpy as np
from PIL import Image, ImageDraw
# Make sure that caffe is on the python path:
caffe_root = '/home/xiaohua/ssd/caffe'
os.chdir(caffe_root)
sys.path.insert(0, os.path.join(caffe_root, '/home/xiaohua/ssd/caffe/python'))
import caffe
import math
from google.protobuf import text_format
from caffe.proto import caffe_pb2
#the mysql_connect function
import pymysql
conn = pymysql.connect(user='root', password='123456', database='qiye2', charset='utf8')
cursor = conn.cursor()
#打印更新字段
def update_data(data_id,figure):
	query = ('update grf_car_tool set figure=%s,zan=%s,update_time=now() where id = %s')
	cursor.execute(query, (figure,figure,data_id))
#更新数据函数
def print_update_info(data_id):
    filed_name= ('select title from grf_car_tool where id = %s')
    cursor.execute(filed_name, (data_id))
    names=cursor.fetchone()
    print names[0],"更新成功"
#更新参数总函数
def update_parameter(data_id,figure):
	update_data(data_id,figure)
	print_update_info(data_id)

# 计算目标点偏移小车角度
def calc_angle(xmin,ymin,pic_width,pic_height):
    vertical_edge=ymin #竖直距离
    horizontal_edge=(xmin/2)-pic_width #水平距离
    tan_angle=vertical_edge/horizontal_edge #/计算出tanα
    final_angle=math.atan(tan_angle)*180/3.1415926 #算出目标偏移小车角度
    if final_angle>-90 and final_angle<0:#目标点在区域左边
        final_angle=-90-final_angle
    elif final_angle>=0 and final_angle<90:#目标点在区域右边
        final_angle=90-final_angle
    else:
        final_angle=0
    print '偏离舵机中线角度=',final_angle
    return final_angle
# 计算目标图片距离
def calc_pic_distance(xmin,ymin,pic_width,pic_height):
    vertical_edge=ymin #竖直距离
    horizontal_edge=(xmin/2)-pic_width #水平距离
    pic_distance=math.sqrt(vertical_edge**2+horizontal_edge**2)
    print '目标的图片距离=',pic_distance
    return pic_distance
# 计算目标实际距离
def calc_real_distance(pic_width,longth):
    image_longth=pic_width
    x_grass=longth
    m1=image_longth*0.2
    m2=image_longth*0.4
    m3=image_longth*0.6
    m4=image_longth*0.8
    m5=image_longth
    if (x_grass>0 and x_grass<m1):
        real_distance=x_grass*10
    elif (x_grass>=m1 and x_grass<m2):
        real_distance=image_longth*2+(x_grass-image_longth*0.2)*30
    elif (x_grass>=m2 and x_grass<m3):
        real_distance=image_longth*2+image_longth*6+(x_grass - image_longth*0.4)*50
    elif (x_grass>=m3 and x_grass<m4):
        real_distance=image_longth*2+image_longth*6+image_longth*10+(x_grass-image_longth*0.6)*70
    elif (x_grass>=m4 and x_grass<=m5):
        real_distance=image_longth*2+image_longth*6+image_longth*10+image_longth*14+(x_grass- image_longth*0.8)*90
    else:
        real_distance=0
    print '目标真实距离为：',real_distance
    return real_distance

# 定义各函数完毕
def get_labelname(labelmap, labels):
    num_labels = len(labelmap.item)
    labelnames = []
    if type(labels) is not list:
        labels = [labels]
    for label in labels:
        found = False
        for i in xrange(0, num_labels):
            if label == labelmap.item[i].label:
                found = True
                labelnames.append(labelmap.item[i].display_name)
                break
        assert found == True
    return labelnames

class CaffeDetection:
    def __init__(self, gpu_id, model_def, model_weights, image_resize, labelmap_file):
        caffe.set_device(gpu_id)
        caffe.set_mode_gpu()

        self.image_resize = image_resize
        # Load the net in the test phase for inference, and configure input preprocessing.
        self.net = caffe.Net(model_def,      # defines the structure of the model
                             model_weights,  # contains the trained weights
                             caffe.TEST)     # use test mode (e.g., don't perform dropout)
         # input preprocessing: 'data' is the name of the input blob == net.inputs[0]
        self.transformer = caffe.io.Transformer({'data': self.net.blobs['data'].data.shape})
        self.transformer.set_transpose('data', (2, 0, 1))
        self.transformer.set_mean('data', np.array([104, 117, 123])) # mean pixel
        # the reference model operates on images in [0,255] range instead of [0,1]
        self.transformer.set_raw_scale('data', 255)
        # the reference model has channels in BGR order instead of RGB
        self.transformer.set_channel_swap('data', (2, 1, 0))

        # load PASCAL VOC labels
        file = open(labelmap_file, 'r')
        self.labelmap = caffe_pb2.LabelMap()
        text_format.Merge(str(file.read()), self.labelmap)

    def detect(self, image_file, conf_thresh=0.5, topn=5):
        '''
        SSD detection
        '''
        # set net to batch size of 1
        # image_resize = 300
        self.net.blobs['data'].reshape(1, 3, self.image_resize, self.image_resize)
        image = caffe.io.load_image(image_file)

        #Run the net and examine the top_k results
        transformed_image = self.transformer.preprocess('data', image)
        self.net.blobs['data'].data[...] = transformed_image

        # Forward pass.
        detections = self.net.forward()['detection_out']

        # Parse the outputs.
        det_label = detections[0,0,:,1]
        det_conf = detections[0,0,:,2]
        det_xmin = detections[0,0,:,3]
        det_ymin = detections[0,0,:,4]
        det_xmax = detections[0,0,:,5]
        det_ymax = detections[0,0,:,6]

        # Get detections with confidence higher than 0.6.
        top_indices = [i for i, conf in enumerate(det_conf) if conf >= conf_thresh]

        top_conf = det_conf[top_indices]
        top_label_indices = det_label[top_indices].tolist()
        top_labels = get_labelname(self.labelmap, top_label_indices)
        top_xmin = det_xmin[top_indices]
        top_ymin = det_ymin[top_indices]
        top_xmax = det_xmax[top_indices]
        top_ymax = det_ymax[top_indices]

        result = []
        for i in xrange(min(topn, top_conf.shape[0])):
            xmin = top_xmin[i] # xmin = int(round(top_xmin[i] * image.shape[1]))
            ymin = top_ymin[i] # ymin = int(round(top_ymin[i] * image.shape[0]))
            xmax = top_xmax[i] # xmax = int(round(top_xmax[i] * image.shape[1]))
            ymax = top_ymax[i] # ymax = int(round(top_ymax[i] * image.shape[0]))
            score = top_conf[i]
            label = int(top_label_indices[i])
            label_name = top_labels[i]
            result.append([xmin, ymin, xmax, ymax, label, score, label_name])
        return result

def main(args):
    '''main '''
    detection = CaffeDetection(args.gpu_id,
                               args.model_def, args.model_weights,
                               args.image_resize, args.labelmap_file)
    result = detection.detect(args.image_file)
    print result

    img = Image.open(args.image_file)
    draw = ImageDraw.Draw(img)
    width, height = img.size
    print "width","height"
    print width, height
    for item in result:
        xmin = int(round(item[0] * width))
        ymin = int(round(item[1] * height))
        xmax = int(round(item[2] * width))
        ymax = int(round(item[3] * height))
        draw.rectangle([xmin, ymin, xmax, ymax], outline=(255, 0, 0))
        draw.text([xmin, ymin], item[-1] + str(item[-2]), (0, 0, 255))
        xmin = int(round(item[0] * width))
        if xmin<=0:
            xmin=0
        ymin = height-int(round(item[3] * height)) #int(round(item[1] * height))
        if ymin<=0:
            ymin=0
        xmax = int(round(item[2] * width))
        if xmax>=width:
            xmax=width
        ymax =height-int(round(item[1] * height)) #int(round(item[3] * height))
        if ymax>=height:
            ymax=height
        print item
        print "xmin","ymin","xmax","ymax"
        print [xmin,ymin, xmax,ymax]
        print "xmin","ymin","label_nmae"
        print [xmin,ymin],item[-1]
    img.save('/home/xiaohua/data/capture_form_pi/data_of_pic/result_pic/detect_result.jpg')
#更新 目标图片宽度
    update_parameter(14,width)
#更新 目标图片高度
    update_parameter(15,height)
#更新 目标图片距离
    pic_distance=calc_pic_distance(xmin,ymin,width,height)

#更新 目标图片最小值横坐标
    update_parameter(6,xmin)
#更新 目标图片最小值纵坐标
    update_parameter(5,ymin)

#更新 目标图片最大值纵坐标
    update_parameter(7,ymax)

#更新 目标图片最大值横坐标
    update_parameter(8,xmax)

#更新 目标实际最小值横坐标
    xmin_real_distance=calc_real_distance(width,xmin)
    update_parameter(10,xmin_real_distance)

#更新 目标实际最小值纵坐标
    ymin_real_distance=calc_real_distance(width,ymin)
    update_parameter(11,ymin_real_distance)

#更新 目标实际最大值横坐标
    xmax_real_distance=calc_real_distance(width,xmax)
    update_parameter(12,xmax_real_distance)

#更新 目标实际最大值纵坐标
    ymax_real_distance=calc_real_distance(width,ymax)
    update_parameter(13,ymax_real_distance)

#更新 目标实际角度
    angle=calc_angle(xmin,ymin,width,height)
    update_parameter(2,angle)
#更新 目标实际距离
    goal_real_distance=calc_real_distance(width,pic_distance)
    update_parameter(3,goal_real_distance)

#更新 目标实际区域面积
    goal_real_area=(xmax_real_distance-xmin_real_distance)*(ymax_real_distance-ymin_real_distance)
    update_parameter(4,goal_real_area)


def parse_args():
    '''parse args'''
    parser = argparse.ArgumentParser()
    parser.add_argument('--gpu_id', type=int, default=0, help='gpu id')
    parser.add_argument('--labelmap_file',
                        default='/home/xiaohua/ssd/caffe/data/VOCdevkit/VOC2007/labelmap_voc.prototxt')
    parser.add_argument('--model_def',
                        default='/home/xiaohua/ssd/caffe/models/VGGNet/SSD_300x300/deploy.prototxt')
    parser.add_argument('--image_resize', default=300, type=int)
    parser.add_argument('--model_weights',
                        default='/home/xiaohua/ssd/caffe/models/VGGNet/SSD_300x300/'
                        'VGG_grass_test_SSD_300x300_iter_120000.caffemodel')
    parser.add_argument('--image_file', default='/home/xiaohua/data/capture_form_pi/data_of_pic/pi_pic/2.jpg')
    return parser.parse_args()

if __name__ == '__main__':
    main(parse_args())
end=time.clock()
print('running time:%s seconds'%(end-start))
update_parameter(1,(end-start))